package AgentesConcurso;

import jade.lang.acl.ACLMessage;
import java.util.GregorianCalendar;


import Ontologias.OntologiaConcursoFornecedores;
import Ontologias.VeiculoPedido;
import Ontologias.PredicadoConcurso;
import jade.content.lang.sl.SLCodec;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.wrapper.AgentController;
import jade.wrapper.ContainerController;
import jade.wrapper.StaleProxyException;


@SuppressWarnings("serial")
public class SubmeterConcurso extends jade.core.Agent{

	PredicadoConcurso pred_conc;



	@SuppressWarnings("unused")
	public void setup() {
		
		getContentManager().registerLanguage(new SLCodec());
		getContentManager().registerOntology(OntologiaConcursoFornecedores.getInstance());

		try {
			// REGISTO DO AGENTE NAS PAGINAS AMARELAS
			DFAgentDescription dfd = new DFAgentDescription();
			dfd.setName( getAID() );
			ServiceDescription sd  = new ServiceDescription();
			sd.setType( "SubmeterConcurso" );
			sd.setName( getLocalName() );
			dfd.addServices(sd);

			DFService.register(this, dfd );  
		}
		catch (FIPAException fe) { fe.printStackTrace(); }

		pred_conc = new PredicadoConcurso();
		CriaConcursoUI ccUI = new CriaConcursoUI(this);

	}

	public void registar_concurso() {

		pred_conc.setData_inicio(new GregorianCalendar());


	}



	public void send_concurso(PredicadoConcurso pConc) {

		int nForn = 0;

		ACLMessage cfp = new ACLMessage(ACLMessage.CFP);


		DFAgentDescription dfd = new DFAgentDescription();
		ServiceDescription sd  = new ServiceDescription();
		sd.setType( "Fornecedor" );
		dfd.addServices(sd);

		DFAgentDescription[] result = {};
		try {
			result = DFService.search(this, dfd);

		} catch (FIPAException e) {
			e.printStackTrace();
		}


		for (DFAgentDescription df : result) {
			cfp.addReceiver(df.getName());
			nForn++;
		}


		try {

			cfp.setContentObject(pConc);

			this.addBehaviour(new PrazoConcurso(this,pConc, cfp,nForn));

		} catch (Exception ce) {
			ce.printStackTrace();
		}

		send(cfp);


	}


	public void adicionar_veiculo (String nome,String tipoProduto, int nUnidades, String combustivel, int lotacaoMin, int pesoCargaMin, int volumeCargaMin) {

		VeiculoPedido veic = new VeiculoPedido();
		veic.setnUnidades(nUnidades);
		veic.setLotacaoMin(lotacaoMin);
		veic.setPesoCargaMin(pesoCargaMin);
		veic.setVolumeCargaMin(volumeCargaMin);

		pred_conc.getVeicPedidos().add(veic);

	}



	public void criar_loading(int tempo,String nome, GregorianCalendar data) {

		ContainerController cc;
		AgentController ac;
		Object[] args_list = new Integer[1];
		args_list[0] = tempo;

		cc = getContainerController();
		try {
			ac = cc.createNewAgent("loader_" + nome + "_" + data.getTimeInMillis(),"AgentesConcurso.AgenteLoading", args_list);
			ac.start();
		} catch (StaleProxyException e) {
			e.printStackTrace();
		}


	}


}
